//
//  SLAbroadRegisterViewController.m
//  CoolMove
//
//  Created by WSL on 15/10/7.
//  Copyright © 2015年 CA. All rights reserved.
//

#import "SLAbroadRegisterViewController.h"
#import "FUIAlertView.h"
#import "UIColor+Extension.h"
#import "MBProgressHUD+HudTools.h"
#import "MBProgressHUD+Add.h"

@interface SLAbroadRegisterViewController () <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *emailTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (weak, nonatomic) IBOutlet UITextField *confirmTextField;
@property (weak, nonatomic) IBOutlet UIButton *signUpButton;


@end

@implementation SLAbroadRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self configureLocalization];
    [self customizeAppearance];
    [self registerNotification];
}

- (void)configureLocalization {
    self.title = NSLocalizedString(@"E-mail Sign Up", nil);
    self.passwordTextField.placeholder = NSLocalizedString(@"Login.Varify", nil);
    self.confirmTextField.placeholder = NSLocalizedString(@"Confirm password", nil);
    
    [self.signUpButton setTitle:NSLocalizedString(@"Sign up", nil) forState:UIControlStateNormal];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Notification

- (void)registerNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleTextFieldDidChange) name:UITextFieldTextDidChangeNotification object:nil];
}

- (void)handleTextFieldDidChange
{
    if (self.emailTextField.isFirstResponder) {
        self.emailTextField.text = [self.emailTextField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    }
}

#pragma mark - Private Method

- (void)customizeAppearance
{
    self.emailTextField.tintColor = [UIColor lightGrayColor];
    self.passwordTextField.tintColor = [UIColor lightGrayColor];
    self.confirmTextField.tintColor = [UIColor lightGrayColor];
}

- (IBAction)registerByEmail:(UIButton *)sender {
    
    if (self.emailTextField.isFirstResponder) {
        [self.emailTextField resignFirstResponder];
    } else if (self.passwordTextField.isFirstResponder) {
        [self.passwordTextField resignFirstResponder];
    } else if (self.confirmTextField.isFirstResponder) {
        [self.confirmTextField resignFirstResponder];
    }
    
    if (!_emailTextField.text.length&&!_passwordTextField.text.length) {
        FUIAlertView *alertView = [[FUIAlertView alloc] initWithTitle:NSLocalizedString(@"Reminder", nil) message:NSLocalizedString(@"please enter a email address and password", nil)  delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        
        [alertView customizeAppearance];
        [alertView show];

        return;
    }
    
    if (!_emailTextField.text.length) {
        FUIAlertView *alertView = [[FUIAlertView alloc] initWithTitle:NSLocalizedString(@"Reminder", nil) message:NSLocalizedString(@"Please enter your email address", nil) delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        
        [alertView customizeAppearance];
        [alertView show];

        return;
    }
    
    if (![self verifyEmail]) {
        FUIAlertView *alertView = [[FUIAlertView alloc] initWithTitle:NSLocalizedString(@"Reminder", nil) message:NSLocalizedString(@"Please enter a valid email address", nil)  delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        
        [alertView customizeAppearance];
        [alertView show];
        
        return;
    }
    
    
    if (!_passwordTextField.text.length) {
        FUIAlertView *alertView = [[FUIAlertView alloc] initWithTitle:NSLocalizedString(@"Reminder", nil) message:NSLocalizedString(@"Please enter a password", nil) delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        
        [alertView customizeAppearance];
        [alertView show];
        return;
    }
    
    if (![self verifyPassword]) {
        FUIAlertView *alertView = [[FUIAlertView alloc] initWithTitle:NSLocalizedString(@"Reminder", nil) message:NSLocalizedString(@"Passwords should be a combination of 6-16 letters, numbers and underscores", nil) delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alertView customizeAppearance];
        [alertView show];

        return;
    }
    
    if (![_passwordTextField.text isEqualToString:_confirmTextField.text]) {
        FUIAlertView *alertView = [[FUIAlertView alloc] initWithTitle:NSLocalizedString(@"Reminder", nil) message:NSLocalizedString(@"Password and confirm password must be identical", nil)  delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alertView customizeAppearance];
        [alertView show];

        return;
    }
    
    YFLoginApi *api = [YFLoginApi emailSignInOrSignUp:NO email:self.emailTextField.text password:self.passwordTextField.text];
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [[YFNetworkingService sharedInstance] sendRequest:api callback:^(BOOL success, id result, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (success) {
            if (self.delegate&&[self.delegate respondsToSelector:@selector(registerFinish:password:)]) {
                [self.delegate registerFinish:_emailTextField.text password:_passwordTextField.text];
                [self.navigationController popViewControllerAnimated:YES];
            }
            [MBProgressHUD showTextHUDWithMessage:NSLocalizedString(@"Registered successfully", nil) inView:self.view];
        } else {
            NSInteger ret = [((YTKBaseRequest *)result).responseJSONObject[@"ret"] integerValue];
            if (ret == -2 || ret == -11001) {
                FUIAlertView *alertView = [[FUIAlertView alloc] initWithTitle:NSLocalizedString(@"Reminder", nil) message:NSLocalizedString(@"This email address has already been registered", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
                [alertView customizeAppearance];
                [alertView show];
            } else {
                [MBProgressHUD showTextHUDWithMessage:NSLocalizedString(@"Registered Fail", nil) inView:self.view];
            }
        }
    }];
}

- (BOOL)verifyPassword{
    NSString *passwordRegex = @"^[a-zA-Z0-9_-]{6,16}$";
    NSPredicate *passwordVerify = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passwordRegex];
    return [passwordVerify evaluateWithObject:_passwordTextField.text];
}

- (BOOL)verifyEmail{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailVerify = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailVerify evaluateWithObject:_emailTextField.text];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [_passwordTextField resignFirstResponder];
    [_emailTextField resignFirstResponder];
    [_confirmTextField resignFirstResponder];
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if ([textField isEqual:self.emailTextField] && textField.text.length > 0) {
        if (self.passwordTextField.text.length == 0) {
            [self.passwordTextField becomeFirstResponder];
        } else if (self.confirmTextField.text.length == 0) {
            [self.confirmTextField becomeFirstResponder];
        } else {
            [textField resignFirstResponder];
        }
    } else if ([textField isEqual:self.passwordTextField] && textField.text.length > 0) {
        if (self.confirmTextField.text.length == 0) {
            [self.confirmTextField becomeFirstResponder];
        } else {
            [textField resignFirstResponder];
        }
    } else {
        if (textField.text.length > 0) {
            [textField resignFirstResponder];
            [self registerByEmail:nil];
        }
    }
    
    return YES;
}

@end
